<template>
  <div class="global-container">
    <div
      class="global-header"
      style="background-color: #fff; margin-bottom: 20px; height: 70px"
    >
      <div class="searchDiv1" style="height: 50px">
        <div style="font-size: 24px; font-weight: bold; margin-right: 50px">
          服务列表
        </div>
        <div style="display: flex; align-items: center">
          <div
            @click="handleSearch"
            style="font-size: 15px; font-weight: lighter"
          >
            <span class="keyword">关键词：</span>
          </div>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入服务名称或标识"
            @input="handleSearch"
            style="width: 200px"
          >
          </el-input>
        </div>
      </div>
      <!-- 按钮部分，批量删除和服务注册按钮 -->
      <div style="display: flex; float: right">
        <el-button
          type="danger"
          class="el-button-primary-style"
          @click="batchDelete"
          :disabled="selectedServices.length === 0"
          :style="{ borderRadius: '4px' }"
          style="margin-right: 10px"
        >
          批量删除
        </el-button>
        <el-button
          class="el-button-primary-style"
          type="primary"
          @click="registerService"
          :style="{ borderRadius: '4px' }"
          style="margin-right: 20px"
        >
          服务注册
        </el-button>
      </div>
    </div>

    <div
      class="servicePackageList"
      style="display: flex; flex-direction: column; height: 100vh"
    >
      <!-- 服务列表表格 -->
      <div style="flex: 1; overflow: auto">
        <el-table
          :data="serviceList"
          style="width: 100%"
          border
          header-class-name="custom-header"
          @selection-change="handleSelectionChange"
        >
          <!-- 复选框列 -->
          <el-table-column
            type="selection"
            width="55"
            align="center"
            header-class-name="custom-header"
          ></el-table-column>

          <el-table-column
            label="序号"
            type="index"
            width="80 "
            align="center"
            header-class-name="custom-header"
          >
            <template slot-scope="scope">
              <!-- Calculate the sequence number based on the current page and page size -->
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            label="服务名称"
            prop="serviceName"
            align="center"
            header-class-name="custom-header"
          ></el-table-column>
          <el-table-column
            label="服务标识"
            prop="interfaceContractList"
            align="center"
            header-class-name="custom-header"
          ></el-table-column>
          <el-table-column
            label="服务提供者"
            prop="serviceProviderInformation"
            align="center"
            header-class-name="custom-header"
          ></el-table-column>
          <el-table-column
            label="服务状态"
            prop="serviceOpenness"
            width="80"
            align="center"
            header-class-name="custom-header"
          ></el-table-column>
          <el-table-column
            label="发布状态"
            prop="servicePublishStatus"
            width="80"
            align="center"
            header-class-name="custom-header"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            header-class-name="custom-header"
          >
            <template slot-scope="scope">
              <el-button
                @click="viewDetails(scope.row)"
                size="mini"
                type="text"
                style="padding: 0; font-size: 15px"
                >详情 |</el-button
              >
              <el-button
                @click="editService(scope.row)"
                size="mini"
                type="text"
                style="padding: 0 2px; font-size: 15px"
                >编辑 |</el-button
              >
              <el-button
                @click="deleteService(scope.row)"
                size="mini"
                type="text"
                style="font-size: 15px"
                >删除 |</el-button
              >
              <el-dropdown
                @command="(command) => moreAction(command, scope.row)"
                style="margin-left: 10px"
              >
                <el-button size="mini" type="text" style="font-size: 15px">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="action1"
                    >流量控制</el-dropdown-item
                  >
                  <el-dropdown-item command="action2"
                    >身份认证</el-dropdown-item
                  >
                  <el-dropdown-item command="action3"
                    >安全防护</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div
        style="
          margin-top: 10px;
          float: right;
          display: flex;
          justify-content: flex-end;
        "
      >
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 服务详情弹窗 -->
    <div>
      <el-dialog
        :visible.sync="detailInfoDialog"
        title="服务详情"
        style="font-weight: bold; font-size: 18px; color: #303133"
        width="50%"
        :before-close="beforeClosePortsDetailDialog"
      >
        <!-- 基本信息部分 -->
        <div class="basic-info">
          <div>
            <span style="font-weight: bold; font-size: 18px; color: #303133"
              >基本信息</span
            >
          </div>
          <div class="info-row">
            <div
              class="info-item"
              style="display: flex; align-items: center; margin-right: 20px"
            >
              <span
                style="display: inline-block; width: 80px; margin-right: 10px"
                >服务名称</span
              >
              <el-input
                v-model="serviceInfo.serviceName"
                disabled
                style="width: 400px"
              />
            </div>
            <div class="info-item" style="display: flex; align-items: center">
              <span
                style="display: inline-block; width: 80px; margin-right: 10px"
                >服务标识</span
              >
              <el-input
                v-model="serviceInfo.interfaceContractList"
                disabled
                style="width: 400px"
              />
            </div>
          </div>
          <div class="info-row">
            <div
              class="info-item"
              style="display: flex; align-items: center; margin-right: 20px"
            >
              <span
                style="display: inline-block; width: 80px; margin-right: 10px"
                >中文名称</span
              >
              <el-input
                v-model="serviceInfo.serviceTitle"
                disabled
                style="width: 400px"
              />
            </div>
            <div class="info-item" style="display: flex; align-items: center">
              <span
                style="display: inline-block; width: 80px; margin-right: 10px"
                >服务地址</span
              >
              <el-input
                v-model="serviceAddress"
                disabled
                style="width: 400px"
              />
            </div>
          </div>
          <div class="info-row">
            <div class="info-item" style="display: flex; align-items: center">
              <span
                style="display: inline-block; width: 80px; margin-right: 10px"
                >服务描述</span
              >
              <el-input
                v-model="serviceInfo.serviceDescription"
                disabled
                style="width: 400px"
                type="textarea"
              />
            </div>
          </div>
        </div>

        <!-- 端口信息部分 -->
        <div style="margin-top: 20px">
          <span style="font-weight: bold; font-size: 18px; color: #303133"
            >端口信息</span
          >
        </div>
        <div
          class="endpoint-info"
          v-if="
            serviceInfo.serviceInstanceList &&
            serviceInfo.serviceInstanceList.length > 0 &&
            serviceInfo.serviceInstanceList[0].portInfoList
          "
        >
          <el-table
            :data="serviceInfo.serviceInstanceList[0].portInfoList"
            style="width: 100%; margin-top: 20px"
            border
          >
            <el-table-column
              label="端口协议"
              prop="type"
              align="center"
            ></el-table-column>
            <el-table-column
              label="内部端口"
              prop="port"
              align="center"
            ></el-table-column>
            <el-table-column
              label="外部端口"
              prop="port"
              align="center"
            ></el-table-column>
          </el-table>
        </div>

        <!-- 底部关闭按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="detailInfoDialog = false"
            type="info"
            class="el-button-primary-style"
            >关闭</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: "",
      serviceList: [],
      currentPage: 1,
      pageSize: 10,
      serviceInfo: { serviceInstanceList: [] },
      detailInfoDialog: false,
      total: 0,
      selectedServices: [], // 用于存储选中的服务项
      loading: false, // 用于显示加载状态
      param: {
        filterKey: "",
        pageNum: 1, // Set initial page number to 1
        pageSize: 10,
      },
    };
  },
  computed: {
    serviceAddress() {
      return this.serviceInfo.serviceInstanceList &&
        this.serviceInfo.serviceInstanceList.length > 0
        ? this.serviceInfo.serviceInstanceList[0].ip
        : "无服务地址";
    },
  },
  methods: {
    async fetchServiceData() {
      this.loading = true; // 开启加载状态
      console.log("Fetching data with params:", this.param); // Debugging line to check params
      try {
        const response = await this.$serviceListApi.getServiceList(this.param); // ✅ 调用 API 获取数据
        // console.log("Backend data:", response.data);
        // console.log("ID", response.data.records[0].id);
        // Debugging line to check response
        if (response && response.data) {
          this.serviceList = response.data.records || []; // ✅ 赋值服务列表

          this.total = response.data.total || this.serviceList.length; // ✅ 赋值总数
        }
      } catch (error) {
        console.error("获取服务列表失败:", error);
      } finally {
        this.loading = false; // 关闭加载状态
      }
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.param.pageNum = page; // Directly use page number in your params
      this.fetchServiceData(); // 重新加载数据
    },

    handleSearch() {
      this.currentPage = 1; // 搜索时重置为第一页
      this.param.filterKey = this.searchKeyword; // 根据你的后端API要求，可能需要filterKey
      this.fetchServiceData(); // 重新加载数据
    },
    handleSelectionChange(val) {
      this.selectedServices = val;
    },

    getServiceIp(row) {
      return row.records?.[0]?.ip || "无"; // 兼容空数据
    },
    // 展示服务详情弹窗
    async viewDetails(row) {
      this.loading = true; // 开启加载状态
      console.log("Row", row);
      try {
        const response = await this.$serviceListApi.getServiceDetails(row.id); // 调用 API 获取服务详细信息
        console.log("viewDetails Response", response);
        if (response && response.data) {
          row.serviceInstanceList = [{ ...response.data }]; // 合并serviceInstanceList数据
          this.serviceInfo = row; // 赋值服务详情信息
          console.log("serviceInfo", this.serviceInfo);
          this.detailInfoDialog = true; // 显示详情弹窗
        }
      } catch (error) {
        console.error("获取服务详情失败:", error);
      } finally {
        this.loading = false; // 关闭加载状态
      }
    },
    beforeClosePortsDetailDialog() {
      this.detailInfoDialog = false; // 关闭详情弹窗
    },

    async editService(row) {
      this.loading = true; // 开启加载状态
      try {
        const response = await this.$serviceListApi.getServiceDetails(row.id); //  调用 API 获取服务详细信息
        // console.log("editService Response", response);
        if (response && response.data) {
          row.serviceInstanceList = [{ ...response.data }]; // 合并serviceInstanceList数据
          this.$router.push({
            name: "ServiceEdit",
            params: {
              serviceData: row,
              refreshCallback: this.fetchServiceData, // 传递回调函数
            },
          });
        }
      } catch (error) {
        console.error("获取服务详情失败:", error);
      } finally {
        this.loading = false; // 关闭加载状态
      }
    },

    async deleteService(row) {
      console.log("Row", row);
      // 检查并转换 interfaceContractList
      if (typeof row.interfaceContractList === "string") {
        row.interfaceContractList = row.interfaceContractList.split(",");
      }

      // 检查并转换 keywordList
      if (typeof row.keywordList === "string") {
        row.keywordList = row.keywordList.split(",");
      }
      const serviceId = row.id;
      console.log("serviceId", serviceId);
      this.$confirm(`确定删除服务 ${row.serviceName}?`, "警告", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
      })
        .then(async () => {
          try {
            const response = await this.$serviceListApi.deleteService([
              serviceId,
            ]);
            if (response && response.code === 200) {
              this.$message.success("服务已删除");
              this.fetchServiceData(); // 重新加载数据
            } else {
              this.$message.error("删除服务失败");
            }
          } catch (error) {
            console.error("删除服务失败:", error);
            this.$message.error("删除服务失败");
          }
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },

    async batchDelete() {
      if (this.selectedServices.length === 0) {
        this.$message.warning("请先选择要删除的服务");
        return;
      }

      this.$confirm(
        `确定删除选中的 ${this.selectedServices.length} 项服务吗？`,
        "警告",
        {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
        }
      )
        .then(async () => {
          try {
            const ids = this.selectedServices.map((service) => service.id);
            console.log("ids", ids);
            const response = await this.$serviceListApi.deleteService(ids);
            if (response && response.code === 200) {
              this.$message.success("服务已删除");
              this.fetchServiceData(); // 重新加载数据
            } else {
              this.$message.error("删除服务失败");
            }
          } catch (error) {
            console.error("删除服务失败:", error);
            this.$message.error("删除服务失败");
          }
        })
        .catch(() => {
          this.$message.info("取消删除");
        });
    },

    registerService() {
      this.$router.push("/ServiceList/service-register"); //  确保正确的路由
    },

    moreAction(command, row) {
      switch (command) {
        case "action1":
          this.$message.info(`流量控制：${row.serviceTitle}`);
          break;
        case "action2":
          this.$message.info(`身份认证：${row.serviceTitle}`);
          break;
        case "action3":
          this.$message.info(`安全防护：${row.serviceTitle}`);
          break;
        default:
          this.$message.warning("未知操作");
      }
    },
  },
  mounted() {
    this.fetchServiceData(); // 页面加载时获取数据
  },
};
</script>

<style scoped>
.global-header {
  display: flex;
  justify-content: space-between; /* 将内容两端对齐 */
  align-items: center; /* 垂直居中对齐 */
  padding: 10px; /* 可选：添加一些内边距 */
}

.basic-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item {
  width: 48%; /* Slightly less than half for two items per row */
}

.info-item span {
  display: inline-block;
  width: 100%; /* Ensure the text aligns correctly */
}

.endpoint-info .el-table {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #304156;
}
</style>
